<template>
  <!-- 查询 -->
  <el-form :inline="true" :model="queryData">
    <template v-for="item in queryConfig" :key="item.id">
      <!-- 输入框 -->
      <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label">
        <el-input v-model="queryData[item.field]" :placeholder="'请输入' + item.label" />
      </el-form-item>
    </template>

    <!-- 按钮 -->
    <template v-if="queryConfig.length">
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="" :icon="RefreshRight" @click="reset">重置</el-button>
      </el-form-item>
    </template>
    <!-- <el-form-item>
      <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
    </el-form-item> -->
  </el-form>

  <!-- 表格 -->
  <el-table :data="tableData" v-loading="loading" height="calc(100vh - 85px)" table-layout="auto" stripe>
    <template v-for="item in props.config.data" :key="item.id">
      <!-- 字典 -->

      <el-table-column v-if="item.type == 'select'" :label="item.label">
        <template #default="scope">
          <template v-for="opt in item.options">
            <template v-if="scope.row[item.field] == opt.value">{{
    opt.label
  }}</template>
          </template>
        </template>
      </el-table-column>

      <!-- 图片 -->
      <el-table-column v-else-if="item.type == 'image'" :label="item.label">
        <template #default="scope">
          <!-- <el-image style="width: 80px; height: 80px" :src="baseURL + scope.row[item.prop]" fit="contain" /> -->
          <img style="width: 80px; height: 80px" :src="baseURL + scope.row[item.field]" />
        </template>
      </el-table-column>

      <!-- 默认 -->
      <el-table-column v-else :prop="item.field" :label="item.label">
        <template #default="scope">
          <div v-html="scope.row[item.field]" class="aaa"></div>
        </template>
      </el-table-column>
    </template>

    <el-table-column v-if="props.config.API.edit || props.config.API.del" fixed="right" label="操作" width="140">
      <template #default="scope">
        <el-button v-if="props.config.API.edit" link type="primary" size="small" :icon="Edit"
          @click="edit(scope.row)">编辑</el-button>
        <el-popconfirm v-if="props.config.API.del" title="确认删除此项?" confirm-button-text="确认" cancel-button-text="取消"
          @confirm="del(scope.row.id)">
          <template #reference>
            <el-button link type="danger" size="small" :icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination background layout="prev, pager, next" :total="count" @change="pageChange" />

  <!-- 表单 -->
  <el-dialog v-model="visible" title="新增/编辑" width="600">
    <el-form :model="formData" ref="formRef" :rules="rules">
      <template v-for="item in formConfig" :key="item.id">
        <!-- 文本 -->
        <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label" :prop="item.field"
          :label-width="labelWidth">
          <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" clearable />
        </el-form-item>

        <!-- 文本域 -->
        <el-form-item v-if="item.type == 'textarea'" :label="item.label" :prop="item.field" :label-width="labelWidth">
          <el-input v-model="formData[item.field]" :rows="2" type="textarea" :placeholder="'请输入' + item.label"
            clearable />
        </el-form-item>

        <!-- 密码框 -->
        <el-form-item v-if="item.type == 'password'" :label="item.label" :prop="item.field" :label-width="labelWidth">
          <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" show-password clearable />
        </el-form-item>

        <!-- 选择 -->
        <el-form-item v-if="item.type == 'select'" :label="item.label" :prop="item.field" :label-width="labelWidth">
          <el-select v-model="formData[item.field]" :placeholder="'请选择' + item.label" style="width: 240px">
            <el-option v-for="item in item.options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 数字框 -- 月份-->
        <el-form-item v-if="item.type == 'number' && item.field == 'count'" :label="item.label" :prop="item.field"
          :label-width="labelWidth">
          <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" :min="1" />
        </el-form-item>

        <!-- 价格 -->
        <el-form-item v-if="item.type == 'number' && item.field == 'price'" :label="item.label" :prop="item.field"
          :label-width="labelWidth">
          <!-- <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" /> -->
          <el-input-number v-model="formData[item.field]" :precision="item.precision || 2" :min="0" :step="0.01" />
        </el-form-item>

        <!-- 上传 -->
        <el-form-item v-if="item.type == 'image'" :label="item.label" :label-width="labelWidth">
          <el-upload class="avatar-uploader" :action="uploadURL" :show-file-list="false" name="file" accept="image/*"
            :on-success="(res) => (formData[item.field] = res.src)">
            <img v-if="formData[item.field]" :src="baseURL + formData[item.field]" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item v-if="item.type == 'editor'" type="number" :label="item.label" :prop="item.field"
          :label-width="labelWidth">
          <Editor :value="content" @updateValue="getMsg" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" @click="submit(formRef)"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- <Pagination :total="total" @changeSize="handlerChangeSize" @changeCurrent="handlerChangeCurrent" /> -->
</template>

<script setup>
import { ref, defineProps, reactive } from "vue";
import {
  Search,
  RefreshRight,
  Plus,
  Edit,
  Delete,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { baseURL, uploadURL } from "@/api/config.json";
import Editor from "@/components/Editor/index.vue";
import Pagination from "@/components/Pagination.vue";

const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {
        API: {
          get: Promise.resolve(),
          add: Promise.resolve(),
          edit: Promise.resolve(),
          del: Promise.resolve(),
        },
        data: [],
      };
    },
  },
});
const total = ref(75);
const handlerChangeSize = (size) => {
  queryData.pageSize = size;
  getData();
};
const handlerChangeCurrent = (num) => {
  queryData.pageNum = num;
  getData();
};
const notice_board  = ref();
const getMsg = (val) => {
  formData.value.notice_board  = val;
};
const labelWidth = 180;
const clear = (obj) => {
  for (const key in obj) {
    queryData[key] = "";
  }
};

// 查询
const queryData = reactive({
  pageSize: 10,
  pageNum: 1,
});
const queryConfig = ref(props.config.data.filter((i) => i.query));
const reset = () => {
  clear(queryData);
  getData();
};

// 列表
const page = ref(1);
const count = ref();
const loading = ref(false);
const tableData = ref([]);
const getData = () => {
  if (!props.config.API.get) return console.log("required API.get method");
  loading.value = true;
  let token = localStorage.getItem("token");
  const queryParams = Object.assign(queryData, { user_token: token });

  props.config.API.get(queryParams)?.then((res) => {
    console.log(res)
    tableData.value = [res.data];
    loading.value = false;
  });
};
getData();

const pageChange = (currentPage) => {
  page.value = currentPage;
  getData();
};

// 新增/编辑
const visible = ref(false);
const formRef = ref();
const formData = ref({});
const formConfig = ref(props.config.data.filter((i) => i.operate));
const rules = ref({});
props.config.data.map((item) => {
  if (item.required) {
    rules.value[item.field] = [
      {
        required: true,
        message: `${item.type == "select" ? "请选择" : "请输入"}${item.label}`,
        trigger: "blur",
      },
    ];
  }
});

const add = () => {
  clear(formData.value);
  visible.value = true;
};

const edit = (row) => {
  console.log(row.notice_board , "123");
  notice_board .value = row.content;
  formData.value = { ...row };
  visible.value = true;
};

const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      const data = { ...formData.value };
      let token = localStorage.getItem("token");
      data.user_token = token;
      const API = data.id ? props.config.API.edit : props.config.API.add;
      data.vip_id = data.id;
      API(data).then((res) => {
        if (res.code == 0) {
          visible.value = false;
          ElMessage.success("操作成功");
          getData();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

// 删除
const del = (id) => {
  let token = localStorage.getItem("token");
  props.config.API.del({ vip_id: id, user_token: token }).then(
    (res) => {
      if (res.code == 0) {
        ElMessage.success("删除成功");
        getData();
      } else {
        ElMessage.error(res.msg);
      }
    }
  );
};
</script>
<style scoped>
.el-pagination {
  margin-top: 18px;
  justify-content: flex-end;
}

:deep(.cell img) {
  width: 100px !important;
  height: 100px !important;
}

:deep(.avatar-uploader .avatar) {
  width: 120px;
  height: 120px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>